import { defineStore } from "pinia";
import { ref } from "vue";
import { v4 as uuid } from 'uuid';
import { MsgType } from "../constants/chat";
import { api } from "../api/service";
import { EventSourceParserStream } from "eventsource-parser/stream";

export const useChat = defineStore('chat', () => {
    const messages = ref([])
    
    function pushMsg(msg) {
        messages.value.push(msg)
    }

    function deleteMsg(index) {
        messages.value.splice(index, 1)
    }

    async function send(msg) {
        const userMsg = {
            id: uuid(),
            content: msg,
            role: MsgType.USER
        }
        pushMsg(userMsg)
        const replyMsg = {
            id: uuid(),
            content: "",
            role: MsgType.OTHER
        }
        pushMsg(replyMsg)
        const res = await sendSse(userMsg)
        if (res) {
            console.info('removeLatestMessage111')
            deleteMsg(-1, 1)
        }
    }

    const loading = ref(false)

    const controller = ref(null)

    function abort() {
        controller.value?.abort()
    }

    async function sendSse(sendData) {
        loading.value = true
        try {
            controller.value = new AbortController()
            const response = await fetch(api.completeConversation, {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify(sendData),
                signal: controller.value.signal,
            })

            const res = response.clone().json();
            const reader = response?.body
                ?.pipeThrough(new TextDecoderStream())
                .pipeThrough(new EventSourceParserStream())
                .getReader();
            
            while (reader) {
                const { done, value } = await reader.read()
                if (done) {
                    console.info('done');
                    break
                }
                
                try {
                    const val = JSON.parse(value?.data || '')
                    const d = val?.data
                    if (typeof d !== 'boolean') {
                        const last = messages.value.length - 1
                        if (last >= 0) {
                            messages.value[last].content = d
                        }
                    }
                } catch (e) {
                    console.warn('Parse error:', e)
                }
            }
            console.info('done?');
            return { data: await res, response };
        } catch (error) {
            console.warn('catch error: ', error)
        } finally {
            loading.value = false
        }
    }

    return { messages, deleteMsg, loading, send, abort }
})